package com.hgyc.mom.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hgyc.mom.common.enums.CommonStatus;
import com.hgyc.mom.common.enums.SysYesNoEnum;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hgyc.mom.base.mapper.BomMapper;
import com.hgyc.mom.base.entity.Bom;
import com.hgyc.mom.base.entity.BomItem;
import com.hgyc.mom.base.service.BomItemService;
import com.hgyc.mom.base.vo.BomVO;
import com.hgyc.mom.base.service.BomService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import com.hgyc.mom.common.exception.BizException;
import org.springframework.util.CollectionUtils;

/**
 * 产品BOMService业务层实现
 *
 * @author fwj
 * @since 2025-07-10
 */
@Slf4j
@Service
public class BomServiceImpl extends ServiceImpl<BomMapper, Bom> implements BomService {

    @Autowired
    private BomItemService bomItemService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveBom(BomVO bomVO) {
        if (checkExist(bomVO)) {
            throw new BizException("产品["+bomVO.getMaterialName()+"] " + bomVO.getVersion() + " 已存在，请修改版本号!");
        }

        save(bomVO);

        //新增产品BOM
        List<BomItem> items = bomVO.getAddItems();
        if (!CollectionUtils.isEmpty(items)) {
            items.forEach(item -> {
                item.setId(null);
                item.setBomId(bomVO.getId());
            });
            bomItemService.saveBatch(items);
        }
    }

    private Boolean checkExist(Bom bom) {
        LambdaQueryWrapper<Bom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bom::getMaterialId, bom.getMaterialId());
        queryWrapper.eq(Bom::getVersion, bom.getVersion());

        return exists(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateBom(BomVO bomVO) {
        // TODO 其他逻辑
        updateById(bomVO);

        //删除产品BOM
        if (!CollectionUtils.isEmpty(bomVO.getDeleteItemIds())) {
            bomItemService.removeBatchByIds(bomVO.getDeleteItemIds());
        }

        //新增产品BOM
        List<BomItem> items = bomVO.getAddItems();
        if (!CollectionUtils.isEmpty(items)) {
            items.forEach(item -> {
                item.setId(null);
                item.setBomId(bomVO.getId());
            });
            bomItemService.saveBatch(items);
        }

        //更新产品BOM
        if (!CollectionUtils.isEmpty(bomVO.getUpdateItems())) {
            List<BomItem> updateItems = bomVO.getUpdateItems();
            bomItemService.updateBatchById(updateItems);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeBom(List<Long> ids) {
        // TODO 其他逻辑
        removeByIds(ids);
        //删除产品BOM
        bomItemService.deleteBatchByParentIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStatus(Bom bom) {
        // 如果更新为启用，而且未默认版本
        if(CommonStatus.ENABLE.getValue().toString().equals(bom.getStatus())
                && SysYesNoEnum.Y.getValue().equals(bom.getIsDefault())) {
            // 把该产品的其他版本的是否为默认版本设置为否
            LambdaUpdateWrapper<Bom> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Bom::getIsDefault, SysYesNoEnum.N.getValue());
            updateWrapper.eq(Bom::getMaterialId, bom.getMaterialId());
            update(updateWrapper);
        }

        //更新状态
        LambdaUpdateWrapper<Bom> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Bom::getStatus, bom.getStatus());
        updateWrapper.eq(Bom::getId, bom.getId());
        update(updateWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setDefault(Bom bom) {
        if(SysYesNoEnum.Y.getValue().equals(bom.getIsDefault())) {
            LambdaUpdateWrapper<Bom> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(Bom::getIsDefault, SysYesNoEnum.N.getValue());
            updateWrapper.eq(Bom::getMaterialId, bom.getMaterialId());
            update(updateWrapper);
        }

        //更新
        LambdaUpdateWrapper<Bom> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Bom::getIsDefault, bom.getIsDefault());
        updateWrapper.eq(Bom::getId, bom.getId());
        update(updateWrapper);

    }

    @Override
    public List<BomItem> getBomByProduct(Long productId) {
        LambdaQueryWrapper<Bom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Bom::getMaterialId, productId);
        queryWrapper.eq(Bom::getIsDefault,  SysYesNoEnum.Y.getValue());
        Bom bom = getOne(queryWrapper, false);
        if (bom == null) {
            throw new BizException("该产品没有维护默认的产品BOM，请维护产品BOM信息");
        }

        List<BomItem> bomItemList = bomItemService.getByParentId(bom.getId());
        if (CollectionUtils.isEmpty(bomItemList)) {
            throw new BizException("该产品没有维护物料信息，请维护产品BOM信息");
        }

        return bomItemList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String importData(List<Bom> bomList, boolean updateSupport) {
        if (bomList == null || bomList.isEmpty()) {
            throw new IllegalArgumentException("导入数据不能为空");
        }

        try {
            if (updateSupport) {
                // TODO 实现更新已有数据的导入逻辑
                return "更新导入成功，共导入 " + bomList.size() + " 条数据";
            } else {
                // TODO 实现不更新已有数据的导入逻辑
                return "新增导入成功，共导入 " + bomList.size() + " 条数据";
            }
        } catch (Exception e) {
            log.error("产品BOM导入失败", e);
            throw new BizException("产品BOM导入失败：" + e.getMessage());
        }
    }
}